/*
  该代码用于测试从键盘(stdin)读取数据，写入管道，读取管道，写到屏幕(stdout)
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>


#define SIZE 100


void testPipe()
{
   int fds[2];
   char buffer[SIZE];
   int len;
   if(pipe(fds) == -1)
   {
      perror("make pipe error");
      exit(1);
   }

   //read from stdin
   while(fgets(buffer, sizeof(buffer), stdin))
   {
       len = strlen(buffer);
       //write to pipe
       if(write(fds[1], buffer, len) != len)
       {
          perror("write to pipe error");
          break;
       }
       
       //清空buffer，方便下次读取
       memset(buffer, 0x00, sizeof(buffer));

       //read from pipe
       if(len = read(fds[0], buffer, sizeof(buffer)) == -1)
       {
           perror("read from pipe error");
           break;
       }

       //write to stdout
       write(1, buffer,sizeof(buffer));
   }
}

int main()
{
    testPipe();
    return 0;
}
